package cz.cvut.fel.gfupan.gui.action;

import cz.cvut.fel.gfupan.gui.Session;
import cz.cvut.fel.gfupan.gui.util.Bundle;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ExitAction extends WindowAdapter implements ActionListener {

    private JFrame root;

    public ExitAction(JFrame root) {
        this.root = root;
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        close();
    }

    @Override
    public void windowClosing(WindowEvent evt) {
        close();
    }

    private void close() {
        if (Session.getInstance().isChanged()) {
            int n = showConfirmDialog();
            if (n == JOptionPane.YES_OPTION) {
                if (showFileChooser()) {
                    System.exit(0);
                }
            } else if (n == JOptionPane.NO_OPTION) {
                System.exit(0);
            }
        } else {
            System.exit(0);
        }
    }

    private boolean showFileChooser() throws HeadlessException {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showSaveDialog(root);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            //save file
            return true;
        }
        return false;
    }

    private int showConfirmDialog() {
        return JOptionPane.showConfirmDialog(root,
                Bundle.get("Window.saveChanges"),
                Bundle.get("Window.title"),
                JOptionPane.YES_NO_CANCEL_OPTION);
    }
}